package com.xh.baselibrary.callback;

import android.util.Log;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author xh
 */
public abstract class RetrofitCallback<T extends Object> implements Callback<T> {

    public static final String ERROR_TIME_OUT="socketTimeOut";
    public static final String ERROR_RUN_TIME="runTimeError";
    public static final String ERROR_CONNECT="connectError";
    public static final String ERROR_OTHER="otherError";

    public RetrofitCallback(){
        super();

    }
    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        if (response.raw().code() == 200) {//200是服务器有合理响应
           onSuccess(response);

    } else {//失败响应
        String s = response.errorBody().byteStream().toString();
        Log.i("请求失败", s);
        onFailure(call, new RuntimeException(s));
    }
}

    @Override
    public void onFailure(Call<T> call, Throwable t) {//网络问题走该回调


        if (t instanceof SocketTimeoutException) {
            onError(ERROR_TIME_OUT,t.getMessage());
        } else if (t instanceof ConnectException) {
            onError(ERROR_CONNECT,t.getMessage());
        } else if (t instanceof RuntimeException) {

            onError(ERROR_RUN_TIME,t.getMessage());
            Log.d("error,error代码错误", t.getMessage());
        }else {
            onError(ERROR_OTHER,t.getMessage());
            Log.d("error,error其他错误", t.getMessage());
        }
    }

    protected abstract void onError(String type,String messgae);



    protected abstract void onSuccess(Response<T> response);


}
